import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { message, Skeleton } from 'antd'
import ReactEchartsCore from 'echarts-for-react/lib/core'
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { TitleComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import style from './Style.module.less'
import { addResizeEvent, delResizeEvent } from '@redux/actions'
import { colors } from '@js/config'
import { strToNum } from '@src/assets/js/tool'
echarts.use([PieChart, TitleComponent, CanvasRenderer])
// 单位为万
const moneyCondtionMap = {
  '20万元以下': {
    maxDisputeAmount: 19.999999
  },
  '20-50万元': {
    minDisputeAmount: 20,
    maxDisputeAmount: 49.999999
  },
  '50-100万元': {
    minDisputeAmount: 50,
    maxDisputeAmount: 99.999999
  },
  '100-500万元': {
    minDisputeAmount: 100,
    maxDisputeAmount: 499.999999
  },
  '500-1000万元': {
    minDisputeAmount: 500,
    maxDisputeAmount: 999.999999
  },
  '1000-5000万元': {
    minDisputeAmount: 1000,
    maxDisputeAmount: 4999.999999
  },
  '5000-1亿元': {
    minDisputeAmount: 5000,
    maxDisputeAmount: 9999.999999
  },
  '1亿以上': {
    minDisputeAmount: 10000
  }
}

class AcceptStatistic extends Component {
  state = {
    colors,
    list: [],
    total: 0,
    ready: true
  }

  getPercent (v) {
    const { total } = this.state
    if (v && total) {
      return Math.round(v / total * 10000) / 100 + '%'
    }
  }

  // 获取数据
  getData () {
    this.setState({ loading: true })
    this.$get('/api/xapc/casestat/statDisputeAmount', {
      condition: this.props.condition
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        const d = {
          list: res.data.casenum,
          total: res.data.casenum.reduce((a, b) => ({ value: strToNum(a.value) + strToNum(b.value) })).value
        }
        this.setState(d, () => this.props.onChange(d))
      } else {
        message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 获取类型中文名
  getTypeCn () {
    const map = {
      accept_datetime: '收案',
      docket_datetime: '立案',
      closure_datetime: '结案'
    }
    return map[this.props.type]
  }

  // 获取配置
  getOptions () {
    const data = this.state.list.map((li, i) => {
      const d = {
        ...li,
        itemStyle: {
          color: this.state.colors[i]
        }
      }
      if (i === 0) {
        d.label = {
          show: true
        }
      }
      return d
    })
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        show: false
      },
      series: [
        {
          name: '立案情况',
          type: 'pie',
          radius: ['50%', '70%'],
          itemStyle: {
            borderWidth: 5,
            borderType: 'solid',
            borderColor: 'rgba(255, 255, 255, 1)'
          },
          label: {
            show: false,
            position: 'center',
            formatter: `{a|案件数}\n{b|${this.state.total}件}`,
            rich: {
              a: {
                color: '#7E889C',
                lineHeight: 20,
                fontSize: 16
              },
              b: {
                color: '#1F2229',
                lineHeight: 40,
                fontSize: 24
              }
            }
          },
          data
        }
      ]
    }
  }

  // 点击表格前往详情
  chartClickHandle (e) {
    const { formData } = this.props
    this.props.addWindow({ id: 'AllCaseManage', title: '全委案件', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData: { ...formData, ...moneyCondtionMap[e.name] } } })
  }

  componentDidUpdate (prev) {
    if (prev.searchVersion !== this.props.searchVersion) {
      this.getData()
    }
  }

  componentDidMount () {
    this.getData()
    this.props.addResizeEvent({
      name: 'acceptStatistic',
      handle: () => this.setState({ ready: false }, () => {
        setTimeout(() => {
          this.setState({ ready: true })
        }, 100)
      })
    })
  }

  componentWillUnmount () {
    this.props.delResizeEvent('acceptStatistic')
  }

  // 渲染选择列表
  renderList () {
    return this.state.list.map((li, i) => {
      const p = this.getPercent(li.value)
      return (
        <li className={style.li} key={i}>
          <span className={style['li-title']}>
            <span className={style['li-tag']} style={{ backgroundColor: this.state.colors[i] }} />
            <span className={style['li-title__text']}>{li.name}</span>
          </span>
          <span className={style['li-value']}>
            <span className={style['li-value__percent']}>{p}</span>
            <span className={style['li-value__split']} />
            <span className={style['li-value__text']}>{li.value}</span>
          </span>
        </li>
      )
    })
  }

  render () {
    const onEvents = { click: this.chartClickHandle.bind(this) }
    return (
      <div className={style.block}>
        <div className={style['block-header']}>
          <span className={style['block-header__title']}>标的分布情况</span>
        </div>
        <div className={style['block-body']}>
          <Skeleton loading={this.state.loading}>
            <div className={style['chart-box']}>
              {this.state.ready ? <ReactEchartsCore style={{ width: '100%', height: '100%' }} echarts={echarts} onEvents={onEvents} option={this.getOptions()} /> : null}
            </div>
            <div className={style['list-box']}>
              <ul className={style.list}>
                {this.renderList()}
              </ul>
            </div>
          </Skeleton>
        </div>
      </div>
    )
  }
}

AcceptStatistic.propTypes = {
  condition: PropTypes.string,
  formData: PropTypes.object,
  searchVersion: PropTypes.number,
  onChange: PropTypes.func,
  type: PropTypes.string
}
AcceptStatistic.defaultProps = {
  condition: JSON.stringify([]),
  searchVersion: Date.now(),
  formData: undefined,
  onChange: () => {},
  type: 'accept_datetime'
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addResizeEvent: i => dispatch(addResizeEvent(i)),
    delResizeEvent: i => dispatch(delResizeEvent(i))
  }
})

export default connect(mapState, mapDispatch)(AcceptStatistic)
